<?php
/**
 * 后台管理 - 异步脚本
 * 
 * @version $Id$
 */

class Module_script
{
	/**
	 * 构造函数
	 */
	function __construct() {
		
	}
	
	/**
	 * 在线
	 */
	function online() {
		$time_now = time();
		$time_ts_buffer = $time_now - 120; // 缓冲2分钟
		
		$Db = loadLib('Db');


		// 获取15分钟内的在线用户
		$time_5_ts = $time_ts_buffer - ($time_ts_buffer % (5 * 60));
		$time_15_ts = $time_ts_buffer - ($time_ts_buffer % (15 * 60));
		$sessions = $Db->getAll("SELECT * FROM `session` WHERE `time` >= {$time_15_ts}");
		
		$skeys = 0;
		$unique_uins = 0;
		if(!empty($sessions)) {
			$skeys = count($sessions);
			$unique_uins_array = array();
			foreach ($sessions as $row) {
				$unique_uins_array[$row['uin']] = 1;
			}
			$unique_uins = count($unique_uins_array);
		}

		// 写入统计库
		$old_data = $Db->getOne("SELECT * FROM `statistics_online` WHERE `time` = {$time_5_ts}");
		if(empty($old_data)) {
			$insert_array = array(
				'time' => $time_5_ts,
				'skeys' => $skeys,
				'unique_uins' => $unique_uins,
			);
			$Db->doInsert('statistics_online' , $insert_array);
			echo "inserted\n";
			echo "SELECT * FROM `session` WHERE `time` >= {$time_15_ts}\n";
			
		} else {
			$insert_array = array(
				'skeys' => $skeys,
				'unique_uins' => $unique_uins,
			);
			$Db->doUpdate('statistics_online' , $insert_array , '`time` = ' . $time_5_ts);
			echo "updated\n";
			echo "SELECT * FROM `session` WHERE `time` >= {$time_15_ts}\n";
		}
		
		echo date('Y-m-d H:i:s' , $time_5_ts) . "\n";
		echo count($sessions) . "\n";
		
		echo "ok\n\n\n";
	}

	function overlord_refresh_level_users() {
		$Db = loadDB('app_collocate');
		$User_Db = loadDb('app_user');

		// 先清空老数据
		$Db->query('TRUNCATE TABLE `app_overlord_level_user` ');

		// 查询总量
		$level_total_count = array();
		$level_count = array();
		$level_array = array();
		for($user_db_index = 1 ; $user_db_index <= 64 ; $user_db_index++) {

			$total_count = $User_Db->getOne("SELECT COUNT(*) as count FROM `user_{$user_db_index}`");
			$total_count = $total_count['count'];

			$loop_step = 10000;
			$loop_count = ceil($total_count / $loop_step);

			echo "Table: user_{$user_db_index}\n";
			echo "Time: " . date("Y-m-d H:i:s") . "\n";
			echo "Total: $total_count\n\n";

		
			$each_level_store = 1000;
			
			
			// 每次查询 1000 个数据
			for($i = 0 ; $i < $loop_count ; $i++) {
				
				$offset = $i * $loop_step;
				$result = $User_Db->getAll("SELECT * FROM `user_{$user_db_index}` LIMIT {$offset} , {$loop_step}");

				foreach($result as $row) {
					$value = unserialize($row['Value']);

					if($value['lv'] <= 3) continue;

					$uin = str_replace('user_' , '' , $row['Key']);
					$lv = $value['lv'];

					if( empty($level_total_count[$lv]) ) {
						$level_total_count[$lv] = 0;
					}
					$level_total_count[$lv]++;

					if( empty($level_array[$lv]) ) {
						$level_array[$lv] = array();
					}
					$level_array[$lv][] = $uin;

					// 如果超过上限，就存储到数据库
					if( count($level_array[$lv]) >= $each_level_store ) {
						// 索引+1
						if(empty($level_count[$lv])) {
							$level_count[$lv] = 0;
						}
						$level_count[$lv]++;

						// 写数据库
						$level_array_str = implode(',' , $level_array[$lv]);
						$level_array_key = "level_user_{$lv}_{$level_count[$lv]}";
						$Db->query("INSERT INTO `app_overlord_level_user` (`Key` , `Value` , `time`) VALUES ('{$level_array_key}' , '{$level_array_str}' , " . time() . ")");

						// 清空
						$level_array[$lv] = array();
					}
				}
			}
		}

		// 全部搞完，处理未处理的数据
		foreach($level_array as $lv => $uin_array) {
			if(empty($uin_array)) continue;

			// 索引+1
			if(empty($level_count[$lv])) {
				$level_count[$lv] = 0;
			}
			$level_count[$lv]++;

			// 写数据库
			$level_array_str = implode(',' , $level_array[$lv]);
			$level_array_key = "level_user_{$lv}_{$level_count[$lv]}";
			$Db->query("INSERT INTO `app_overlord_level_user` (`Key` , `Value` , `time`) VALUES ('{$level_array_key}' , '{$level_array_str}' , " . time() . ")");
		}

		// 处理完成，写入 索引
		$index_key = 'level_user_index';
		$Db->doInsert('app_overlord_level_user' , array(
			'Key' => $index_key,
			'Value' => serialize($level_count),
			'time' => time()
		));


		echo "OK\n";
		print_r($level_total_count);
	}
	/**
	 * 机器人自动驻防
	 */
	function garrison(){
		for ($i = 1001 ; $i < 3200 ; $i++){
			$city_key[] = $i;
		}
		loadLib('App_Overlord_Query');
		$city_info = App_Overlord_Query::allCity($city_key);
		if (!empty($city_info)){
			foreach ($city_info as $k => $row){
				if (empty($row['Value']['hkee']['to_uin'])){
					$key = ltrim($row['Key'] , 'city_');
					//记录无驻防的key
					$generals_key[] = $key;
					//记录无驻防的信息
					$array_city[$key] = $row;
				}
			}
		
			if (!empty($generals_key)){
				$generals_info = App_Overlord_Query::allUin_Generals($generals_key);
		
				if (!empty($generals_info)){
					foreach ($generals_info as $k => $row){
				
						$key = ltrim($row['Key'] , 'generals_');
						//随机取一个
						$generals_id = array_rand($row['Value']);
						//武将可带兵数
						$make_count = intval($row['Value'][$generals_id]['make_count'] / 4);
						$row['Value'][$generals_id]['make'] = array($make_count , $make_count , $make_count , $make_count);
						//武将状态修改
						$row['Value'][$generals_id]['state'] = 1;
						//驻防ID
						$row['Value'][$generals_id]['to_uin'] = $key;
			
						//城池修改
						$array_city[$key]['Value']['hkee']['to_uin'] = $key;
						//驻防将领的ID
						$array_city[$key]['Value']['hkee']['generals'] = $generals_id;
						//驻防将领的名字
						$array_city[$key]['Value']['hkee']['generals_name'] = $row['Value'][$generals_id]['name'];
						
						//执行武将修改
						$code = App_Overlord_Query::alterUin_Generals($key, $row['Value']);
						
						//执行城池修改
						$code = App_Overlord_Query::alterCity($key, $array_city[$key]['Value']);
					}	
				}
			}
		}
	}
}

# end of script
